<template>
    <div class="container">
        <div class="search-bar">
            <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" @change="handleDateChange" />
        </div>
        <div class="table-container">
            <el-table :data="weekData" style="width: 100%">
                <el-table-column prop="index" label="序号" width="80" />
                <el-table-column prop="appointTime" label="日期" />
                <el-table-column prop="week" label="星期" />
                <el-table-column prop="morning" label="早班">
                    <template #default="scope">
                        <div class="switch-box">
                            <div>
                                <el-switch v-model="tableRows[scope.$index].morning.isProduction" inline-prompt
                                    active-text="已排班" inactive-text="未排班"
                                    :disabled="isDisabled({ ...tableRows[scope.$index].morning, dayTime: scope.row.appointTime })"
                                    @change="(e) => { handleSwitchChange(scope.row, '0', e) }" />
                            </div>
                            <div>时间:{{ tableRows[scope.$index].morning.startTime }}-{{
                                tableRows[scope.$index].morning.endTime }}
                            </div>
                            <div>班组名称:{{ tableRows[scope.$index].morning.teamName }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="noon" label="中班">
                    <template #default="scope">
                        <div class="switch-box">
                            <div>
                                <el-switch v-model="tableRows[scope.$index].noon.isProduction" inline-prompt
                                    active-text="已排班" inactive-text="未排班"
                                    :disabled="isDisabled({ ...tableRows[scope.$index].noon, dayTime: scope.row.appointTime })"
                                    @change="(e) => { handleSwitchChange(scope.row, '1', e) }" />
                            </div>
                            <div>时间:{{ tableRows[scope.$index].noon.startTime }}-{{ tableRows[scope.$index].noon.endTime
                                }}
                            </div>
                            <div>班组名称:{{ tableRows[scope.$index].noon.teamName }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="evening" label="晚班">
                    <template #default="scope">
                        <div class="switch-box">
                            <div>
                                <el-switch v-model="tableRows[scope.$index].evening.isProduction" inline-prompt
                                    active-text="已排班" inactive-text="未排班"
                                    :disabled="isDisabled({ ...tableRows[scope.$index].evening, dayTime: scope.row.appointTime })"
                                    @change="(e) => { handleSwitchChange(scope.row, '2', e) }" />
                            </div>
                            <div>时间:{{ tableRows[scope.$index].evening.startTime }}-{{
                                tableRows[scope.$index].evening.endTime }}
                            </div>
                            <div>班组名称:{{ tableRows[scope.$index].evening.teamName }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="all" label="全部">
                    <template #default="scope">
                        <el-switch v-model="tableRows[scope.$index].all.isProduction"
                            :disabled="isAllDisabled(scope.row)" inline-prompt active-text="已全部排班" inactive-text="未全部排班"
                            @change="(e) => { handleSwitchChange(scope.row, 'all', e) }" />
                    </template>
                </el-table-column>
                <el-table-column prop="oper" label="排班">
                    <template #default="scope">
                        <el-button type="primary" :icon="EditPen" circle @click="editApi(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import { ref, computed, defineProps, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axisInstance from '@/utils/http/api';
import dayjs from 'dayjs';
import { Edit, EditPen } from '@element-plus/icons-vue';


export default {
    props: {
        editApi: {
            type: Function,
            required: true
        },
        currentNodeKey: {
            type: String,
            required: true // 根据需要决定是否为必填
        },
        weekDays: {
            type: Object,
            required: true
        }
    },
    setup(props, { expose }) {
        const selectedDate = ref(dayjs().format('YYYY-MM-DD'));
        const weekData = ref([]);
        const switchValue = ref(true);

        const components = {
            Edit,
            EditPen
        };

        const childMethod = (treeId) => {
            axisInstance.post('/api/factoryCalendar/getAllWeek', {
                organizationId: treeId || props.currentNodeKey,
                appointTime: dayjs(selectedDate.value).format('YYYY-MM-DD HH:mm:ss')
            })
                .then(res => {
                    if (res.code !== 200) {
                        ElMessage.error(res.message);
                        return false;
                    }
                    const dateTime = res.data.sort((a, b) => new Date(a.appointTime) - new Date(b.appointTime));
                    const weeks = dateTime.map((item, index) => {
                        return {
                            ...item,
                            chlendarJson: JSON.parse(item.chlendarJson),
                            appointTime: dayjs(item.appointTime).format('YYYY-MM-DD'),
                            index: index + 1
                        }
                    });
                    const currentDayOfWeek = dayjs(selectedDate.value).day();
                    const daysAfter = props.weekDays.length - currentDayOfWeek;
                    const daysBefore = 6 - daysAfter;
                    const currentDate = dayjs(selectedDate.value);
                    const beforeDates = Array.from({ length: daysBefore }, (_, i) => currentDate.subtract(i + 1, 'day').format('YYYY-MM-DD'));
                    const afterDates = Array.from({ length: daysAfter }, (_, i) => currentDate.add(i + 1, 'day').format('YYYY-MM-DD'));
                    const weekDates = [...beforeDates, ...afterDates, selectedDate.value].sort((a, b) => new Date(a) - new Date(b));
                    const groupWeek = weekDates.map((item, index) => {
                        const detail = weeks.find(i => i.appointTime == item)
                        if (detail?.appointTime) {
                            return detail
                        } else {
                            return {
                                appointTime: item,
                                dayEdit: true,
                                chlendarJson: [],
                                index: index + 1,
                                week: props.weekDays[dayjs(item).day()]

                            }
                        }
                    })
                    weekData.value = groupWeek
                });
        }

        const tableRows = computed(() => {
            return weekData.value.map(row => {
                return {
                    morning: tableName(row, '0'),
                    noon: tableName(row, '1'),
                    evening: tableName(row, '2'),
                    all: tableName(row, 'all')
                };
            });
        });

        const tableName = (row, type) => {
            if (type === 'all') {
                const flag = row.chlendarJson.find(i => !i.isProduction);
                if (flag) {
                    return { isProduction: false };
                }
                if (row.chlendarJson.length == 0) {
                    return { isProduction: false };

                }
                return { isProduction: true };
            }
            const rowData = row.chlendarJson.find(i => i.shiftName === type);
            return rowData || {};
        }

        const handleSwitchChange = (row, type, e) => {
            let changeRowData = [];
            if (type === 'all') {
                changeRowData = row.chlendarJson.map(item => ({
                    ...item,
                    isProduction: e
                }));
            } else {
                changeRowData = row.chlendarJson.map(item => {
                    if (item.shiftName === type) {
                        return {
                            ...item,
                            isProduction: e
                        };
                    }
                    return item;
                });
            }

            const paramsData = {
                shiftId: row.shiftId,
                weekList: [row.week],
                startDate: dayjs(row.appointTime).format('YYYY-MM-DD HH:mm:ss'),
                endDate: dayjs(row.appointTime).add(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
                chlendarJson: JSON.stringify(changeRowData),
                organizationId: props.currentNodeKey,
            };
            axisInstance.post('/api/factoryCalendar/create', { ...paramsData })
                .then(res => {
                    if (res.code !== 200) {
                        ElMessage.error(res.message);
                        return false;
                    }
                    ElMessage.success('排班成功');
                    childMethod();
                });
        }

        const editApi = (row) => {
            props.editApi({ ...row, typeDay: 'week' });
        }

        // 计算属性，判断 startTime 是否超过当前时间
        const isDisabled = (row) => {
            const jointDay = row.dayTime + ` ` + row.startTime;
            return !dayjs(jointDay).isAfter(dayjs());
        }

        // 判断“全部”开关是否应该被禁用
        const isAllDisabled = (row) => {
            if (row.chlendarJson.length === 0) {
                return true
            }
            const shifts = row?.chlendarJson.map(i => i?.shiftName);
            return shifts.some(shift => isDisabled({ ...tableName(row, shift), dayTime: row.appointTime }));
        }
        const handleDateChange = (value) => {
            childMethod();
        }
        // 监听 selectedDate 的变化
        // watch(selectedDate, (newDate) => {
        // childMethod();
        // });

        expose({ childMethod });

        return {
            selectedDate,
            weekData,
            switchValue,
            tableRows,
            handleSwitchChange,
            editApi,
            isDisabled,
            isAllDisabled,
            handleDateChange,
            ...components,
        };
    }
};
</script>

<style scoped>
.container {
    padding: 20px;

}

.search-bar {
    margin-bottom: 20px;
}

.table-container {
    margin: 0 auto;
}

.switch-box {
    background: #d9edfe9e;
    width: 140px;
    height: 100px;
    border-radius: 4px;
    padding: 10px 8px;
    display: flex;
    flex-direction: column;
    color: #035beb;
    font-size: 13px;
}
</style>